package authorizationAdmin

import (
	"context"
	"encoding/json"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/authorizationAdmin/logic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	pbAuthorizationAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/authorizationAdmin"
)

func (rpc *auth) Login(ctx context.Context, pb *pbAuthorizationAdmin.LoginReq) (*pbAuthorizationAdmin.LoginResp, error) {
	row, e := logic.Login(ctx, pb.Account, pb.Password)

	if e != nil {
		return nil, businessError.ErrorInfoToRpcError(e)
	}

	pbAdmin := &pbAuthorizationAdmin.Admin{
		Id:              row["id"].(int64),
		Email:           row["email"].(string),
		Username:        row["username"].(string),
		Nickname:        row["nickname"].(string),
		Avatar:          row["avatar"].(string),
		Token:           row["token"].(string),
		TokenExpiryTime: row["token_expiry_time"].(string),
		Status:          int32(row["status"].(int64)),
		LoginTime:       row["login_time"].(string),
		CreateTime:      row["create_time"].(string),
		UpdateTime:      row["update_time"].(string),
	}

	_log(ctx, pb, pbAdmin)

	return &pbAuthorizationAdmin.LoginResp{
		Admin: pbAdmin,
	}, nil
}

func _log(ctx context.Context, pb *pbAuthorizationAdmin.LoginReq, admin *pbAuthorizationAdmin.Admin) {

	jsonString, _ := json.MarshalIndent(pb, "", "  ")

	_, _ = database.Db.GetDefaultDb(ctx).Insert("admin_log", map[string]interface{}{
		"admin_id":    admin.Id,
		"username":    admin.Username,
		"url":         utils.MbSubStr(pb.Url, 0, 255),
		"title":       "登录",
		"content":     string(jsonString),
		"ip":          pb.Ip,
		"useragent":   utils.MbSubStr(pb.Useragent, 0, 1000),
		"create_time": utils.Date("Y-m-d H:i:s"),
	})
}
